package com.agritech.facade;

import com.agritech.chain.*;
import com.agritech.command.*;
import com.agritech.factory.*;
import com.agritech.machine.AgriculturalMachineContext;
import com.agritech.observer.EnvironmentSensor;
import com.agritech.observer.MachineObserver;
import com.agritech.strategy.DefaultPathStrategy;
import com.agritech.strategy.PathPlanner;

import java.util.HashMap;
import java.util.Map;

public class AgriTechSystemFacade {
    private Map<String, AgriculturalMachineContext> machines = new HashMap<>();
    private Map<String, MachineObserver> machineObservers = new HashMap<>();
    private EnvironmentSensor environmentSensor;
    private RemoteControl remoteControl;
    private SafetyHandler safetyChain;

    public AgriTechSystemFacade() {
        // 初始化环境传感器
        this.environmentSensor = new EnvironmentSensor();
        // 初始化遥控器
        this.remoteControl = new RemoteControl();
        // 初始化安全责任链
        setupSafetyChain();
        System.out.println("农业科技系统外观已初始化。");
    }

    private void setupSafetyChain() {
        SafetyHandler emergencyHandler = new EmergencyAvoidanceHandler();
        SafetyHandler pathAdjustmentHandler = new PathAdjustmentHandler();
        SafetyHandler faultHandler = new FaultDetectionHandler();

        emergencyHandler.setNextHandler(pathAdjustmentHandler);
        pathAdjustmentHandler.setNextHandler(faultHandler);
        // 可以根据需要添加更多处理器到链中

        this.safetyChain = emergencyHandler; // 责任链的起点
        System.out.println("安全责任链已配置。");
    }

    // 农机设备管理
    public String addMachine(String machineId, String type) {
        AgriculturalMachineFactory factory = null;
        if ("seeder".equalsIgnoreCase(type)) {
            factory = new SeederFactory();
        } else if ("sprayer".equalsIgnoreCase(type)) {
            factory = new SprayerFactory();
        } else if ("harvester".equalsIgnoreCase(type)) {
            factory = new HarvesterFactory();
        } else {
            return "不支持的农机类型: " + type;
        }

        if (factory != null) {
            com.agritech.factory.AgriculturalMachine createdMachine = factory.createMachine();
            AgriculturalMachineContext machineContext = new AgriculturalMachineContext(machineId, createdMachine.getType());
            machines.put(machineId, machineContext);

            // 为新农机创建并注册观察者
            MachineObserver observer = new MachineObserver(machineId + "_Observer", createdMachine);
            environmentSensor.registerObserver(observer);
            machineObservers.put(machineId, observer);

            System.out.println("外观：已添加农机 [" + machineId + "] 类型 [" + createdMachine.getType() + "] 并注册到环境监测。");
            return "农机 [" + machineId + "] 添加成功。";
        }
        return "农机添加失败。";
    }

    public String getMachineStatus(String machineId) {
        AgriculturalMachineContext machine = machines.get(machineId);
        if (machine != null) {
            machine.displayStatus();
            return "状态已打印到控制台。";
        }
        return "未找到ID为 [" + machineId + "] 的农机。";
    }

    // 农田环境监测
    public void updateEnvironmentData(String data) {
        System.out.println("\n外观：接收到新的环境数据，准备通知所有观察者...");
        environmentSensor.setData(data);
    }

    // 任务执行与控制 (通过命令模式)
    public String startMachineOperation(String machineId) {
        AgriculturalMachineContext machine = machines.get(machineId);
        if (machine != null) {
            Command startCommand = new StartMachineCommand(machine);
            remoteControl.setCommand(startCommand);
            remoteControl.pressButton();
            return "启动命令已发送给农机 [" + machineId + "]";
        }
        return "未找到ID为 [" + machineId + "] 的农机，无法启动。";
    }

    public String stopMachineOperation(String machineId) {
        AgriculturalMachineContext machine = machines.get(machineId);
        if (machine != null) {
            Command stopCommand = new StopMachineCommand(machine);
            remoteControl.setCommand(stopCommand);
            remoteControl.pressButton();
            return "停止命令已发送给农机 [" + machineId + "]";
        }
        return "未找到ID为 [" + machineId + "] 的农机，无法停止。";
    }

    public String workMachineOperation(String machineId) {
        AgriculturalMachineContext machine = machines.get(machineId);
        if (machine != null) {
            Command workCommand = new WorkMachineCommand(machine);
            remoteControl.setCommand(workCommand);
            remoteControl.pressButton();
            return "作业命令已发送给农机 [" + machineId + "]";
        }
        return "未找到ID为 [" + machineId + "] 的农机，无法开始作业。";
    }

    public String undoLastMachineOperation() {
        remoteControl.pressUndoButton();
        return "撤销上一条命令已执行。";
    }

    // 智能路径规划 (通过策略模式，由观察者内部调用，这里可以提供一个手动触发的示例)
    public String planPathForMachine(String machineId, String environmentInfo) {
        MachineObserver observer = machineObservers.get(machineId);
        if (observer != null) {
            System.out.println("\n外观：为农机 [" + machineId + "] 手动触发路径规划，环境信息: " + environmentInfo);
            // 模拟观察者接收到信息并规划路径
            observer.update(environmentInfo); 
            return "路径规划已为农机 [" + machineId + "] 执行。";
        }
        return "未找到ID为 [" + machineId + "] 的农机观察者，无法规划路径。";
    }

    // 安全事件处理 (通过责任链模式)
    public void reportSafetyEvent(String eventType, String details) {
        System.out.println("\n外观：报告安全事件，类型: " + eventType + ", 详情: " + details);
        safetyChain.handleRequest(eventType, details);
    }

    // 模拟系统管理功能
    public void logOperation(String machineId, String operation) {
        System.out.println("系统日志: 农机 [" + machineId + "] 执行操作: " + operation);
    }

    public void displayAllMachineStatuses() {
        System.out.println("\n--- 所有农机状态概览 ---");
        if (machines.isEmpty()) {
            System.out.println("当前系统中没有农机。");
            return;
        }
        for (AgriculturalMachineContext machine : machines.values()) {
            machine.displayStatus();
        }
        System.out.println("-------------------------");
    }
}